<template>
  <div>
    <el-upload
      class="show-upload-demo"
      action=""
      :http-request="(file) => {chooseFiles(file)}"
      :on-remove="(file, fileList) => {remove(file, fileList)}"
      :on-preview="onPreview"
      :multiple="chooseFileMultiple"
      :auto-upload="true"
      accept=".xls,.xlsx"
      list-type="text"
    >
      <div style="display: none;" />
      <el-button :disabled="uploadFile ? true : false" size="mini" type="primary" style="margin-right: 12px;"><i class="el-icon-folder-opened" />选择文件</el-button>
    </el-upload>
    <span v-if="!uploadFile" style="display: inline-block;line-height: 40px;font-size: 12px;color: #FF0000;">{{ '请依照模板格式上传“xls”或“xlsx”文件。' }}</span>
  </div>
</template>

<script>
import { get } from '@/api/request'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import { $tooltips } from '@/sun-components/SunMsg.js'
const defaultSettings = require('@/settings.js')
export default {
  name: 'SunImport',
  props: {
    importoptions: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      chooseFileMultiple: false,
      uploadFile: null
    }
  },
  computed: {
    show_sunImport() {
      return this.$parent.$parent.show_sunImport
    },
    download() {
      return this.$parent.$parent.importoptions.download
    },
    upload() {
      return this.$parent.$parent.importoptions.upload
    }
  },
  watch: {
    download(val) {
      if (val) {
        this.getDownloadTemplate()
      }
    },
    upload(val) {
      if (val) {
        this.submitUploadFile()
      }
    }
  },
  methods: {
    /**
     * 选择文件
     */
    async chooseFiles(file) {
      this.$parent.$parent.importoptions.buttonState = true
      this.uploadFile = file
    },
    /**
     * 上传文件
     */
    submitUploadFile() {
      const _that = this
      let api = ''
      if (this.$store.getters.publicRoute === 'user') {
        switch (this.$store.getters.identity) {
          case '1':
            api = process.env.NODE_ENV === 'development' ? `${defaultSettings.developmentApi}/api/principal/${_that.$parent.$parent.importoptions.api}` : `/api/principal/${_that.$parent.$parent.importoptions.api}`
            break
          case '2':
            api = process.env.NODE_ENV === 'development' ? `${defaultSettings.developmentApi}/api/teacher/${_that.$parent.$parent.importoptions.api}` : `/api/teacher/${_that.$parent.$parent.importoptions.api}`
            break
          case '3':
            api = process.env.NODE_ENV === 'development' ? `${defaultSettings.developmentApi}/api/expert/${_that.$parent.$parent.importoptions.api}` : `/api/expert/${_that.$parent.$parent.importoptions.api}`
            break
        }
      }
      if (this.$store.getters.publicRoute === 'admin') {
        api = process.env.NODE_ENV === 'development' ? `${defaultSettings.developmentApi}/api/admin/${_that.$parent.$parent.importoptions.api}` : `/api/admin/${_that.$parent.$parent.importoptions.api}`
      }
      const formData = new FormData()
      const xhr = new XMLHttpRequest()
      _that.$parent.$parent.importoptions.loading = true
      formData.append('file', _that.uploadFile.file)
      xhr.open('post', api, true)
      xhr.setRequestHeader('Authorization', getToken())
      xhr.ontimeout = function timeout() {
        $tooltips('上传超时，请重新上传...', 'warning')
      }
      xhr.send(formData)
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          _that.$parent.$parent.importoptions.loading = false
          _that.$parent.$parent.importoptions.upload = false
        }
        if (xhr.readyState === 4 && (xhr.status === 201 || xhr.status === 200 || xhr.status === 206)) {
          const response = JSON.parse(xhr.response)
          // console.log('导入结果---------', response)
          if (response.code === 0) {
            $tooltips(response.msg, 'success')
            _that.$parent.$parent.show_sunImport = false
            _that.$parent.$parent.upData()
            return
          }
          if (response.code === -1) {
            $tooltips(response.msg, 'error')
            return
          }
          if (response.code === 2006) {
            MessageBox.confirm(`${response.msg},下载查看失败原因`, '提示', {
              confirmButtonText: '下 载',
              cancelButtonText: '取 消',
              type: 'warning'
            }).then((action) => {
              if (action) {
                _that.$parent.$parent.show_sunImport = false
                _that.$parent.$parent.upData()
                window.location.href = response.data.fail_rows
              }
            }).catch(() => {
              _that.$parent.$parent.show_sunImport = false
              _that.$parent.$parent.upData()
            })
          }
        }
      }
    },
    /**
     * 下载模板
     */
    async getDownloadTemplate() {
      await get(`import/templates`).then(response => {
        if (response.code === 0) {
          window.location.href = response.data[this.importoptions.template]
          this.$parent.$parent.importoptions.download = false
        }
      })
    },
    /**
     * 文件预览
     */
    async onPreview(file) {
      // console.log('文件预览')
    },
    /**
     * 删除
     */
    async remove(file, fileList) {
      if (!fileList.length) {
        this.uploadFile = null
        this.$parent.$parent.importoptions.buttonState = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  @import "~@/styles/variables.scss";
</style>
